//
//  UserGroupMapViewController.m
//  MapLink
//
//  Created by student on 5/19/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "UserGroupMapViewController.h"
#import "JSON.h"
#import "MeetingPlaceAnnotationView.h"
#import "AppConfig.h"

@implementation UserGroupMapViewController

@synthesize groupName, displayName, deviceID, delegate, buffer;

-(id) init {
	self = [super initWithNibName:@"UserGroupMapViewController" bundle:nil];
	if(self){
		[[self navigationItem] setTitle:@"Map"];
		locationManager = [[CLLocationManager alloc] init];
		[locationManager setDelegate:self];
		[locationManager startUpdatingLocation];
		currentLocation = (CLLocationCoordinate2D){1.37066586, 103.84292573};
		
		isDragging = NO;
		isGroupOwner = NO;
	}
	return self;
}
-(void)locationManager:(CLLocationManager *)manager
   didUpdateToLocation: (CLLocation *)newLocation
		  fromLocation:(CLLocation *)oldLocation
{	
	NSLog(@"%@", newLocation);
	currentLocation = newLocation.coordinate;
	if (!isDragging) {
		[maMe setCoordinate:currentLocation];
		[mapView setCenterCoordinate:currentLocation  animated:YES];
		[mapView selectAnnotation:maMe animated:NO];
	}
} 

-(void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *) error
{
	NSLog(@"Could not locate location: %@", error);
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] 
											   initWithTitle:@"UnJoin" 
											   style:UIBarButtonItemStyleBordered 
											   target:self action:@selector(unjoin)] autorelease];
	[mapView setDelegate:self];
	
	// structure to define areas spanned by a map region
	MKCoordinateRegion region; 
	region.center = currentLocation;
	// define the distance (in degrees) to be display
	region.span.latitudeDelta = .005;
	region.span.longitudeDelta = .005;
	[mapView setRegion:region animated:TRUE];

	if (maMe == nil) {
		maMe = [[MapAnnotation alloc] initWithCoordinate:currentLocation title:displayName];
	}

	timer=[NSTimer scheduledTimerWithTimeInterval:10
                                           target:self 
                                         selector:@selector(refresh) 
                                         userInfo:nil 
                                          repeats:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	NSLog(@"Group map will appear: %@",displayName);
	
	maMe.subtitle=[NSString stringWithString:@"Click to send notification"];
	[mapView addAnnotation:maMe];
	[mapView selectAnnotation:maMe animated:NO];

    // Change the nav item to display group name
	[[self navigationItem] setTitle:groupName];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(coordinateChanged_:) name:@"DDAnnotationCoordinateDidChangeNotification" object:nil];
	isDragging = NO;
	isGroupOwner = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];	
	[locationManager stopUpdatingLocation];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:@"DDAnnotationCoordinateDidChangeNotification" object:nil];	
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSLog(@"Confirm unjoin");
		[delegate passValue:groupName forKey:@"unjoin"];
		[[self navigationController] popViewControllerAnimated:YES];
    }
}

-(void) refresh {
	NSLog(@"timer");
	NSURL *url = [NSURL URLWithString:[NSString 
									   stringWithFormat:@"http://mybuddies.emiu.net/update.php?device_id=%@&name=%@&group=%@&latitude=%d&longitude=%d",
									   [deviceID stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], 
									   [displayName stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], 
									   [groupName stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], 
									   (int)(currentLocation.latitude*1e6), (int)(currentLocation.longitude*1e6)]];
	if(url == NULL) {
		UIAlertView *alertView = [[UIAlertView alloc] 
								  initWithTitle:@"Error" 
								  message:@"GroupName/password is invalid.\nPlease remove SPACE or any other invalid charactors." 
								  delegate:nil 
								  cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}
	NSLog(@"url is: %@", url);
	NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
	[req setHTTPMethod:@"GET"];
	
	conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
	if (conn) {
		self.buffer = [NSMutableData data]; 
	}	
}
-(void) unjoin {
	NSLog(@"unjoin %@", groupName);
	UIAlertView *alertView = [[UIAlertView alloc] 
							  initWithTitle:@"Unjoin" 
							  message:[NSString stringWithFormat:@"Do you really want to unjoin group \"%@\"", groupName] 
							  delegate:self 
							  cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
	[alertView addButtonWithTitle:@"Yes"];
	[alertView show];
	[alertView release];
}
-(IBAction) findMe {
	NSLog(@"clicked on findMe");
	[mapView setCenterCoordinate:currentLocation  animated:YES];
	[mapView selectAnnotation:maMe animated:YES];
}
-(IBAction) meetingPoint {
	NSLog(@"clicked on meetingPoint");
	
	//only group owner can create a meeting point
	if(isGroupOwner){
		
			
		if(!daMeetingpoint) {
			CLLocationCoordinate2D location = {currentLocation.latitude + .001, currentLocation.longitude +.001};
			daMeetingpoint = [[MeetingPlaceAnnotation alloc] initWithCoordinate:location addressDictionary:nil];
			daMeetingpoint.title = @"Meeting Point (Drag to move)";
			
				//try to reverse lookup and print address
			daMeetingpoint.subtitle = [NSString	stringWithFormat:@"%f %f", daMeetingpoint.coordinate.latitude, daMeetingpoint.coordinate.longitude];
			
			[mapView addAnnotation:daMeetingpoint];
		}
		
	}
	if(daMeetingpoint) {
		[mapView setCenterCoordinate:daMeetingpoint.coordinate  animated:YES];
		[mapView selectAnnotation:daMeetingpoint animated:YES];
	}
}
-(IBAction) displayNotifications {
	NSLog(@"clicked on notification");
	// Check if I need to create the instance
	if (!notificationListViewController) {
		notificationListViewController = [[NotificationListViewController alloc] 
										  initWithDeviceID:deviceID 
										  withUserName:displayName 
										  withGroupName:groupName 
										  withNumberOfNotifications:numberOfNotifications];
	} else {
		notificationListViewController.deviceID = deviceID;
		notificationListViewController.userName = displayName;
		notificationListViewController.groupName = groupName;
		notificationListViewController.newNotifications = numberOfNotifications;
	}
	
	//display a view modally
	[self presentModalViewController:notificationListViewController animated:YES];
}


-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
	[buffer setLength:0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
	[buffer appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
	[buffer release];
	[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
	NSLog(@"Done with bytes %d", [buffer length]);
	NSMutableString *jsonString = [[NSMutableString alloc] initWithBytes:[buffer mutableBytes]
																  length:[buffer length]
																encoding:NSUTF8StringEncoding];
	NSLog(@"result is %@", jsonString);

	if(!isDragging) {
		NSDictionary *response = [jsonString JSONValue];
		NSString *result = [response objectForKey:@"result"];
		if([result isEqualToString:@"Y"]){
			//success
			int notifications = [[response valueForKey:@"notification"] intValue];
			numberOfNotifications = notifications;
			buttonNotification.title = [NSString stringWithFormat:@"Notifications (%d)",notifications];
			
			NSString *owner = [response objectForKey:@"owner"];
			isGroupOwner = [owner isEqualToString:@"Y"];

			[mapView removeAnnotations:mapView.annotations];
			NSArray *buddies = [response objectForKey:@"buddies"];
			for (NSDictionary *buddy in buddies) {
				NSString *name = [buddy objectForKey:@"name"];
				int latitude = [[buddy valueForKey:@"latitude"] intValue];
				int longitude = [[buddy valueForKey:@"longitude"] intValue];
				
				CLLocationCoordinate2D location = {latitude/1e6, longitude/1e6};
				MapAnnotation *ma = [[MapAnnotation alloc] initWithCoordinate:location  title:name];
				[mapView addAnnotation:ma];
				[ma release];
			}

			//meeting point
			NSDictionary *meeting = [response objectForKey:@"meeting"];
			int latitude = [[meeting valueForKey:@"latitude"] intValue];
			int longitude = [[meeting valueForKey:@"longitude"] intValue];
			if( latitude!=0 && longitude!=0){
				CLLocationCoordinate2D location = {latitude/1e6, longitude/1e6};
				if (!daMeetingpoint) {
					daMeetingpoint = [[MeetingPlaceAnnotation alloc] initWithCoordinate:location addressDictionary:nil];
					daMeetingpoint.title = @"Meeting Point (Drag to move)";
					daMeetingpoint.subtitle = [NSString	stringWithFormat:@"%f %f", daMeetingpoint.coordinate.latitude, daMeetingpoint.coordinate.longitude];
				}else{
					daMeetingpoint.coordinate = location;
					daMeetingpoint.subtitle =[NSString	stringWithFormat:@"%f %f", location.latitude, location.longitude];
				}
			}else if(daMeetingpoint){
				[daMeetingpoint release];
				daMeetingpoint = nil;
			}
			if(daMeetingpoint)
				[mapView addAnnotation:daMeetingpoint];
			if(maMe) {
				[mapView addAnnotation:maMe];
				[mapView selectAnnotation:maMe animated:NO];
			}
			[buttonMeetingPoint setEnabled:YES];
		}else{
			//fail
			NSLog(@"upload error: %@",[response objectForKey:@"message"]);
		}
	}
	[jsonString release];
	[connection release];
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
	NSLog(@"Sending notification");
	
	if (!notificationCreateViewController) {
		notificationCreateViewController = [[NotificationCreateViewController alloc] init];
		notificationCreateViewController.displayName = displayName;
		notificationCreateViewController.groupName = groupName;
		notificationCreateViewController.deviceID = deviceID;
		notificationCreateViewController.currentLocation = currentLocation;
	}
	
	[self presentModalViewController:notificationCreateViewController animated:YES];
}



#pragma mark -
#pragma mark MKMapViewDelegate

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState {
	if( newState == MKAnnotationViewDragStateStarting) {
		NSLog(@"DragStart");
		isDragging = YES;
	}
	if (oldState == MKAnnotationViewDragStateDragging) {
		NSLog(@"DragFinish");
		isDragging = NO;
		MeetingPlaceAnnotation *annotation = (MeetingPlaceAnnotation *)annotationView.annotation;
		annotation.subtitle = [NSString	stringWithFormat:@"%f %f", annotation.coordinate.latitude, annotation.coordinate.longitude];
		
		NSURL *url = [NSURL URLWithString:[NSString 
										   stringWithFormat:@"http://mybuddies.emiu.net/meeting.php?device_id=%@&group=%@&latitude=%i&longitude=%i",
										   [deviceID stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], 
										   [groupName stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], 
										   (int)(annotation.coordinate.latitude*1e6), 
										   (int)(annotation.coordinate.longitude*1e6)]];
		if(url == NULL) {
			NSLog(@"invalid url");
		}
		NSLog(@"url is: %@", url);
		NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
		[req setHTTPMethod:@"GET"];
		
		conn = [[NSURLConnection alloc] initWithRequest:req delegate:nil];
		[conn release];		
	}
}

- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}


- (void) mapView: (MKMapView *)mapView didAddAnnotationViews:(NSArray *) views {
	for (MKPinAnnotationView *mkaview in views) {
		if ([mkaview.annotation.title isEqualToString:displayName]) {
			mkaview.pinColor = MKPinAnnotationColorPurple;
			UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
			mkaview.rightCalloutAccessoryView = button;
			mkaview.canShowCallout =YES;
			
			NSString * photopath=[[AppConfig getDocumentFolder] stringByAppendingPathComponent:@"avatar.png"];
			UIImage *img = [UIImage imageWithContentsOfFile:photopath];
			
			if (img) {
				mkaview.leftCalloutAccessoryView = [[UIImageView alloc] initWithImage:[self imageWithImage:img scaledToSize:CGSizeMake(32.0f,32.0f)]];
			} else {
				mkaview.leftCalloutAccessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"profile.png"]];
			}
		} else {
			mkaview.pinColor = MKPinAnnotationColorRed;
			mkaview.canShowCallout =YES;
			mkaview.rightCalloutAccessoryView = nil;
			
			NSString *urlString = [[NSString stringWithFormat:@"http://mybuddies.emiu.net/photo/%@.png",mkaview.annotation.title]
								   stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
			NSURL *url = [NSURL URLWithString:urlString];
			NSData *avatarData = [NSData dataWithContentsOfURL:url];
			
			if (avatarData) {
				mkaview.leftCalloutAccessoryView = [[UIImageView alloc] initWithImage:[self imageWithImage:[UIImage imageWithData:avatarData] scaledToSize:CGSizeMake(32.0f,32.0f)]];
			} else {
				mkaview.leftCalloutAccessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"profile.png"]];
			}
		}

	}
}


- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation {
	
    if ([annotation isKindOfClass:[MapAnnotation class]]) {
		static NSString *AnnotationViewID = @"BuddyPinID";
		MKPinAnnotationView* pinView = 
		(MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
		if (!pinView)
		{
			// if an existing pin view was not available, create one
			MKPinAnnotationView* customPinView = 
			[[[MKPinAnnotationView alloc] initWithAnnotation:annotation 
											 reuseIdentifier:AnnotationViewID] 
			 autorelease];                              
			customPinView.animatesDrop = NO;
			
			return customPinView;
		}
		else
		{
			pinView.annotation = annotation;
		}
		return pinView;	
	}
	
	static NSString * const kPinAnnotationIdentifier = @"MeetingPinID";
	MKAnnotationView *draggablePinView = [mapView dequeueReusableAnnotationViewWithIdentifier:kPinAnnotationIdentifier];
	
	if (draggablePinView) {
		draggablePinView.annotation = annotation;
	} else {
			// Use class method to create DDAnnotationView (on iOS 3) or built-in draggble MKPinAnnotationView (on iOS 4).
		draggablePinView = [MeetingPlaceAnnotationView annotationViewWithAnnotation:annotation reuseIdentifier:kPinAnnotationIdentifier mapView:mapView];
		
		[draggablePinView setDraggable:isGroupOwner];
		
		if ([draggablePinView isKindOfClass:[MeetingPlaceAnnotationView class]]) {
				// draggablePinView is DDAnnotationView on iOS 3.
		} else {
				// draggablePinView instance will be built-in draggable MKPinAnnotationView when running on iOS 4.
		}
	}		
	
	return draggablePinView;
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
	[timer invalidate];
	[mapView release];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
	[notificationListViewController release];
	[locationManager release];
	[delegate release];
	[mapView release];
	[buffer release];
	[maMe release];
	[daMeetingpoint release];
    [super dealloc];
}


@end
